package main

import (
	"bblcloud/bblvolume"
	"flag"
	"log"
	"os"
	"os/signal"
	"path/filepath"
	"runtime"
	"runtime/debug"
	"syscall"
)

var config_file string
var daemon bool

func init() {
	runtime.GOMAXPROCS(runtime.NumCPU() - 1)
	flag.StringVar(&config_file, "c", "/etc/babylon/bblvolumed.conf", "volume server configration")
	flag.BoolVar(&daemon, "d", false, "daemon mode")
	flag.Parse()
}
func main() {
	defer func() {
		if err := recover(); err != nil {
			debug.PrintStack()
		}
	}()
	if daemon && os.Getppid() != 1 {
		filePath, _ := filepath.Abs(os.Args[0])
		args := append([]string{filePath}, os.Args[1:]...)
		os.StartProcess(filePath, args, &os.ProcAttr{Files: []*os.File{os.Stdin, os.Stdout, os.Stderr}})
		return
	}
	sig := make(chan os.Signal)
	signal.Notify(sig, os.Interrupt, os.Kill, syscall.SIGKILL, syscall.SIGTERM, syscall.SIGABRT)
	err := bblvolume.Start(config_file)
	if err != nil {
		log.Fatal(err)
	}
forever:
	for {
		select {
		case <-sig:
			bblvolume.Stop()
			log.Println("[volumed] recv interrupt signal, volume server stopped")
			break forever
		}
	}

}
